package com.chujian.framework.ws.support.rcv;

import com.chujian.framework.ws.WsMsg;
import com.chujian.framework.ws.IWsRcvMsgHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.PriorityOrdered;
import org.springframework.lang.Nullable;
import org.springframework.transaction.annotation.Transactional;


/**
 * 接到消息后，保存到数据库
 * 较高优先级
 */
@Slf4j
public class RcvMsgSaveDbHandler implements IWsRcvMsgHandler, PriorityOrdered {

    private final IWsDbStoreService wsDbStore;

    public RcvMsgSaveDbHandler(@Nullable IWsDbStoreService wsDbStore) {
        this.wsDbStore = wsDbStore;
    }

    @Override
    public boolean canHandle(WsMsg msg, String payload) {
        return null != wsDbStore;
    }

    @Override
    @Transactional
    public WsMsg handle(WsMsg msg, String payload) {
        log.info("接收消息reqId={} 后保存数据库", msg.getReqId());
        if (null != wsDbStore) {
            wsDbStore.saveWsMsg(msg);
        }
        return null;
    }

    @Override
    public int getOrder() {
        return HandlerOrderDef.SAVE_DB;
    }
}
